﻿using gbL.NetBoard.Examples.DoubleMVC.Model.Requests;
using gbL.NetBoard.Examples.DoubleMVC.View.UI.Requests;

namespace gbL.NetBoard.Examples.DoubleMVC.Controller
{
    public class ProductsController
    {
        public Blackboard Domain { get; set; }

        public IInputSource Input { get; set; }

        public ProductsController(Blackboard domain) : this(domain, new ConsoleInputSource()) { }

        public ProductsController(Blackboard domain, IInputSource input)
        {
            Domain = domain;
            Input = input;
        }

        public ControllerDispatch List()
        {
            ProductListRequest request = new ProductListRequest();
            Domain.Add(request);
            return new ControllerDispatch(
                () => new ProductsController(Domain).SelectOrQuit()
            );
        }

        public ControllerDispatch SelectOrQuit()
        {
            ControllerDispatch ret = null;

            Domain.Add(new MessageRequest("ID to view (or enter to return to menu): ", true, false));
            string input = Input.GetLine();

            if (input != "")
            {
                var validation = new ValidateProductRequest() { ProductID = input };
                Domain.Add(validation);
                if (validation.IsValid.Value)
                    ret = new ControllerDispatch(
                        () => new ProductsController(Domain).Detail(input)
                    );
                else
                {
                    Domain.Add(new MessageRequest("Invalid: " + validation.ValidationMessage, false, true));
                    ret = new ControllerDispatch(
                        () => new ProductsController(Domain).SelectOrQuit()
                    );
                }
            }
            else
            {
                ret = new ControllerDispatch(
                    () => new BrowseController(Domain).Products()
                );
            }

            return ret;
        }

        public ControllerDispatch Detail(string productID)
        {
            Domain.Add(new ProductDetailRequest() { ProductID = productID });
            return new ControllerDispatch(
                () => new ProductsController(Domain).SelectOrQuit()
            );
        }
    }
}
